firebase有一個storage,是可以存放圖片空間,今天就是要將圖片上傳到這個地方。
首先,在storage下建立一個post資料夾,待會會把圖片統一傳到這個資料夾。

再來引入之前已經在firebase.js的db和storage
import {db, storage} from "../utils/firebase"
按照官方文件的寫法,檔案就會在storage裡面的post資料夾看到了
//指定post資料夾並給一個唯一值
const storageRef = ref(storage, 'post/' + docId);
//給上傳的檔案額外資訊
const metadata = {
    contentType: imageUpload.type,
};
//上傳時把storageRef,要上傳的檔案以及額外資訊帶入
uploadBytes(storageRef, imageUpload , metadata)
最後是取出已在資料夾中的圖片位置並在按下送出按鈕時傳資料到firebase裡面。
uploadBytes成功後可以使用then來取得圖片網址,一開始不知道可以用這樣的寫法,花了很多時間找取得url的方式,最後看到有人這樣寫,順利的取到值,將值送入先前寫好的data中,onSubmit送出完整資料。
function onSubmit(){
    const newPost = doc(collection(db, "post"));
    //上傳圖片
    const docId = newPost.id
    const storageRef = ref(storage, 'post/' + docId);
    const metadata = {
        contentType: imageUpload.type,
    };
    uploadBytes(storageRef, imageUpload , metadata)
        .then((snapshot)=>{
            return getDownloadURL(snapshot.ref)
        }).then((downloadURL)=>{
            const data = {
                title,
                dateRange,
                continent,
                place,
                content,
                createdAt: serverTimestamp(),
                author:{
                    name: auth.currentUser.email,
                    uid: auth.currentUser.uid
                },
                image:downloadURL
            }
            setDoc(newPost, data);
        })
}
文章編輯頁告一段落!!